/*
 * @lc app=leetcode.cn id=463 lang=typescript
 *
 * [463] 岛屿的周长
 */

// @lc code=start
function islandPerimeter(grid: number[][]): number {
    let final = 0;
    // 遍历所有的格子
    grid.forEach((row, y) =>
        row.forEach((i, x) => {
            // 只有陆地需要计数
            if (i === 1) {
                final += sumAround(x, y, grid);
            }
        })
    );
    return final;
}
// 周长等于四周不是陆地的格子数目
const sumAround = (x: number, y: number, grid: number[][]) => {
    let around = [
        [x + 1, y],
        [x - 1, y],
        [x, y - 1],
        [x, y + 1],
    ];
    return around.reduce((col, [x, y]) => {
        // 数组可能越界
        if (grid?.[y]?.[x] !== 1) return col + 1;
        return col;
    }, 0);
};
// @lc code=end
